package com.fone.player.storage;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;

import com.fone.player.entity.OfflineCache;
import com.fone.player.entity.OfflineCacheFragment;
import com.fone.player.play.VideoPlayerMessage;
import com.fone.player.storage.download.CacheDownloadManager;
import com.fone.player.storage.download.CacheMessageHelper;
import com.fone.player.storage.download.DownloadConstant;
import com.fone.player.storage.download.DownloadUtil;
import com.fone.player.storage.download.StorageManager;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;

import de.greenrobot.event.EventBus;

public class OfflineCacheModule {

	private static final String TAG = OfflineCacheModule.class.getSimpleName();
	private static final OfflineCacheModule mInstance = new OfflineCacheModule();
	/**
	 * 缓存界面存储空间进度信息(内部使用)
	 */
	public static final int MSG_INTERNAL_CACHE_SPACE_SIZE_PROGRESS = 1102;
	/**
	 * 缓存界面中文件删除返回成功(内部使用)
	 */
	public static final int MSG_INTERNAL_FILE_CACHE_DELETE_SUCCESS = 1103;
	/**
	 * 缓存界面中文件下载出错(内部使用)
	 */
	public static final int MSG_INTERNAL_FILE_CACHE_ERROR = 1104;
	/**
	 * 缓存界面(内部使用)
	 */
	public static final int MSG_INTERNAL_CACHE = 1105;
	/**
	 * 收藏界面(内部使用)
	 */
	public static final int MSG_INTERNAL_FAVOURITE = 1106;
	/**
	 * 开始全部(内部使用)
	 */
	public static final int MSG_INTERNAL_START_ALL = 1107;
	/**
	 * 暂停全部(内部使用)
	 */
	public static final int MSG_INTERNAL_PAUSE_ALL = 1108;
	// 是否屏蔽开始全部操作
	private boolean mIsShieldStartAllOperate = false;
	// 是否屏蔽暂停全部操作
	private boolean mIsShieldPauseAllOperate = false;
	// 删除操作是否成功回调
	private boolean mIsDeleteSuccess = false;
	// 添加成功回调
	private boolean mIsAddSuccess = false;
	private LinkedList<CacheOperate> mOperateQueueList = new LinkedList<CacheOperate>();

	private OfflineCacheModule() {
		EventBus.getDefault().register(this);
	}

	public static OfflineCacheModule getInstance() {
		return mInstance;
	}

	public static void init(Context context) {
		L.v(TAG, "init", "start");
		StorageManager.init(context);
		CacheDownloadManager.init(context);
		OperateDataBaseTemplate.init(context);
		DownloadUtil.init(context);
	}

	/**
	 * 
	 * 添加缓存条目集合<br>
	 * 
	 * @param waitOfflineCacheFileList
	 *            等待添加的离线缓存列表
	 * @return int 插入结果<br>
	 *         1 成功 <br>
	 *         -1 插入异常
	 * @throws NullPointerException
	 *             offlineCache为null
	 */
	public int addCacheList(final List<OfflineCache> waitOfflineCacheFileList) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {

					// 获取实际可添加的缓存列表
					List<OfflineCache> actualOfflineCacheFileList = getActualOfflineCacheList(waitOfflineCacheFileList);

					if (actualOfflineCacheFileList != null
							&& actualOfflineCacheFileList.size() > 0) {

						// 添加下载
						CacheDownloadManager.getInstance().addCacheList(
								actualOfflineCacheFileList);
					}

				} catch (Exception e) {

				}
			}
		}).start();

		// 超时10秒钟
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				if (!mIsAddSuccess) {
					// 发送失败消息
					Message msg = new Message();
					msg.what = StorageModule.MSG_ADD_CACHE_FAIL;
					Bundle bundle = new Bundle();
					msg.setData(bundle);
					EventBus.getDefault().post(msg);

					// 发送详情页成功消息
					VideoPlayerMessage videoPlayerMessage = new VideoPlayerMessage();
					videoPlayerMessage.what = StorageModule.MSG_ADD_CACHE_FAIL;
					EventBus.getDefault().post(videoPlayerMessage);
					mIsAddSuccess = true;
				}

			}
		}, 10000);
		return 1;
	}

	/**
	 * 
	 * 获取实际可添加的离线缓存列表
	 * 
	 * @param waitOfflineCacheFileList
	 *            用户选择的离线缓存列表
	 * @return List<OfflineCache>
	 */
	public List<OfflineCache> getActualOfflineCacheList(
			List<OfflineCache> waitOfflineCacheFileList) {
		List<OfflineCache> actualOfflineCacheFileList = new ArrayList<OfflineCache>();

		int notFinishCount = OfflineCacheFileDataBaseAdapter.getInstance()
				.getOfflineCacheFileNotFinishCount();
		int waitCacheCount = waitOfflineCacheFileList.size();
		v(TAG, "getActualOfflineCacheList", "notFinishCount=" + notFinishCount
				+ " waitCacheCount=" + waitOfflineCacheFileList.size());
		// 大于100 不下载
		if (notFinishCount + waitCacheCount > DownloadConstant.MAX_DOWNLOAD_NUM) {

			// 剩余的空位
			int surplusCount = DownloadConstant.MAX_DOWNLOAD_NUM
					- notFinishCount;
			L.w(TAG, "getActualOfflineCacheList",
					"limit DownloadConstant.MAX_DOWNLOAD_NUM surplusCount="
							+ surplusCount);
			// /100tv/video目录
			String offlineCacheRoot = SystemUtil.getInstance()
					.getOfflineCachePath();
			for (int i = 0; i < surplusCount; i++) {

				OfflineCache offlineCache = waitOfflineCacheFileList.get(i);
				// video里面的目录
				String offlineCachePath = CacheMessageHelper.getInstance()
						.getOfflineCacheFileStoragePath(offlineCacheRoot,
								offlineCache);

				offlineCache.setCacheStoragePath(offlineCachePath);
				offlineCache
						.setCacheDownloadState(OfflineCache.CACHE_STATE_WAITING);
				actualOfflineCacheFileList.add(offlineCache);

			}

			L.v(TAG, "getActualOfflineCacheList", "send MSG_MAX_DOWNLOAD");
			Message msg = new Message();
			msg.what = StorageModule.MSG_MAX_DOWNLOAD;
			EventBus.getDefault().post(msg);

		} else {

			// /100tv/video目录
			String offlineCacheRoot = SystemUtil.getInstance()
					.getOfflineCachePath();
			// 全部添加
			for (OfflineCache offlineCache : waitOfflineCacheFileList) {

				// video里面的目录
				String offlineCachePath = CacheMessageHelper.getInstance()
						.getOfflineCacheFileStoragePath(offlineCacheRoot,
								offlineCache);

				offlineCache.setCacheStoragePath(offlineCachePath);
				offlineCache
						.setCacheDownloadState(OfflineCache.CACHE_STATE_WAITING);
				actualOfflineCacheFileList.add(offlineCache);
			}

		}
		return actualOfflineCacheFileList;
	}

	/**
	 * 开始一个条目的下载
	 * 
	 * @return void
	 */
	public void startCache(final OfflineCache offlineCache) {
		v(TAG, "startCache", "start cid=" + offlineCache.getCacheCID());
		new Thread(new Runnable() {

			@Override
			public void run() {

				// 检查网络
				if (!CacheDownloadManager.getInstance().checkNetwork()) {
					return;
				}

				// 判断存储空间
				if (CacheDownloadManager.getInstance()
						.checkSingleStorageSpace()) {
					// 状态设置为暂停
					offlineCache
							.setCacheDownloadState(OfflineCache.CACHE_STATE_PAUSE);
					mergeOfflineCache(offlineCache);
				} else {

					CacheDownloadManager.getInstance().startCache(offlineCache);

				}
			}
		}).start();
	}

	/**
	 * 开始全部下载
	 * 
	 * @return void
	 */
	public void startCacheAll() {
		if (mIsShieldStartAllOperate) {
			L.w(TAG, "startCacheAll", "startCacheAll is running");
			return;
		}

		new Thread(new Runnable() {

			@Override
			public void run() {
				L.v(TAG, "startCacheAll", "start startCacheAll");
				mIsShieldStartAllOperate = true;
				CacheDownloadManager.getInstance().startCacheAll();
			}
		}).start();

		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				// 10秒超时
				mIsShieldStartAllOperate = false;
				mIsShieldPauseAllOperate = false;
			}
		}, 10000);
	}

	/**
	 * 添加到开始全部下载队列
	 * 
	 * @return void
	 */
	public void startCacheAllQueue() {

		if (mIsShieldStartAllOperate) {

			L.v(TAG, "startCacheAllQueue", "operate repeat,clear operate queue");
			mOperateQueueList.clear();

		} else {

			CacheOperate cacheOperate = new CacheOperate();
			cacheOperate.mCacheOperateType = MSG_INTERNAL_START_ALL;
			mOperateQueueList.add(cacheOperate);
			L.v(TAG, "startCacheAllQueue", "add operate queue");

			if (!mIsShieldPauseAllOperate && mOperateQueueList.size() == 1) {
				L.v(TAG, "startCacheAllQueue", "running first operate");
				CacheOperate cacheOperateTemp = mOperateQueueList.removeFirst();
				switch (cacheOperateTemp.mCacheOperateType) {
				case MSG_INTERNAL_START_ALL:
					startCacheAll();
					break;
				default:
					break;
				}
			}
		}

	}

	/**
	 * 添加到暂停全部下载队列
	 * 
	 * @return void
	 */
	public void pauseCacheAllQueue(final boolean isUpdateDownloadState) {

		if (mIsShieldPauseAllOperate) {

			mOperateQueueList.clear();
			L.v(TAG, "pauseCacheAllQueue", "operate repeat,clear operate queue");
		} else {

			CacheOperate cacheOperate = new CacheOperate();
			cacheOperate.mCacheOperateType = MSG_INTERNAL_PAUSE_ALL;
			cacheOperate.mIsUpdateDownloadState = isUpdateDownloadState;
			mOperateQueueList.add(cacheOperate);
			L.v(TAG, "pauseCacheAllQueue", "add operate queue");
			if (!mIsShieldStartAllOperate && mOperateQueueList.size() == 1) {
				L.v(TAG, "pauseCacheAllQueue", "running first operate");
				CacheOperate cacheOperateTemp = mOperateQueueList.removeFirst();
				switch (cacheOperateTemp.mCacheOperateType) {
				case MSG_INTERNAL_PAUSE_ALL:
					pauseCacheAll(cacheOperateTemp.mIsUpdateDownloadState);
					break;
				default:
					break;
				}
			}
		}

	}

	/**
	 * 
	 * 操作等待的操作队列
	 * 
	 * @return void
	 */
	public void operateCacheQueue() {
		if (mOperateQueueList.size() == 0) {
			L.v(TAG, "operateCacheQueue", "no operate,OperateQueue size=0");
			return;
		}

		CacheOperate cacheOperateTemp = mOperateQueueList.removeFirst();
		if (cacheOperateTemp != null) {
			switch (cacheOperateTemp.mCacheOperateType) {
			case MSG_INTERNAL_START_ALL:
				L.v(TAG, "operateCacheQueue",
						"running MSG_INTERNAL_START_ALL operate");
				startCacheAll();
				break;
			case MSG_INTERNAL_PAUSE_ALL:
				L.v(TAG, "operateCacheQueue",
						"running MSG_INTERNAL_PAUSE_ALL operate");
				pauseCacheAll(cacheOperateTemp.mIsUpdateDownloadState);
				break;
			default:
				break;
			}
		}

	}

	/**
	 * 暂停一个条目的下载
	 * 
	 * @return void
	 */
	public void pauseCache(final OfflineCache offlineCache) {

		v(TAG, "pauseCache", "start cid=" + offlineCache.getCacheCID());

		new Thread(new Runnable() {

			@Override
			public void run() {

				CacheDownloadManager.getInstance().pauseCache(offlineCache);

			}
		}).start();

	}

	/**
	 * 暂停所有条目的下载
	 * 
	 * @return void
	 */
	public void pauseCacheAll(final boolean isUpdateDownloadState) {
		if (mIsShieldPauseAllOperate) {
			L.w(TAG, "pauseCacheAll", "pauseCacheAll is running");
			return;
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				L.v(TAG, "pauseCacheAll", "start pauseCacheAll");
				mIsShieldPauseAllOperate = true;
				CacheDownloadManager.getInstance().pauseCacheAll(
						isUpdateDownloadState);
			}
		}).start();

		// 10秒超时
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {
				mIsShieldStartAllOperate = false;
				mIsShieldPauseAllOperate = false;
			}
		}, 10000);
	}

	/**
	 * 删除指定条目列表的下载
	 * 
	 * @return void
	 */
	public void deleteCacheList(final List<OfflineCache> offlineCacheList) {

		new Thread(new Runnable() {

			@Override
			public void run() {

				long startTime = System.currentTimeMillis();

				CacheDownloadManager.getInstance()
						.deleteCache(offlineCacheList);

				long endTime = System.currentTimeMillis();
				L.v(TAG, "deleteCacheList", "delete success intervalTime="
						+ (endTime - startTime));
			}
		}).start();

		// 10秒超时
		new Timer().schedule(new TimerTask() {

			@Override
			public void run() {

				if (!mIsDeleteSuccess) {

					L.v(TAG, "deleteCacheList", "delete timeout");

					mIsDeleteSuccess = true;

					// 删除数据库记录
					CacheDownloadManager.getInstance().deleteCache(
							offlineCacheList);

				} else {
					L.v(TAG, "deleteCacheList",
							"delete timeout already success");
				}

			}
		}, 10000);
	}

	/**
	 * 获取缓存第一级目录集合
	 * 
	 * @return void
	 */
	public void getOfflineCacheFolderList() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				// 获取本地缓存第一级目录集合,根据缓存层级类型填充缓存集合
				ArrayList<OfflineCache> offlineCacheList = OfflineCacheModule
						.getInstance().mergeOfflineCacheFolderList();
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putParcelableArrayList(OfflineCache.OFFLINE_CACHE_LIST,
						offlineCacheList);
				message.what = StorageModule.MSG_FOLDER_CACHE_LIST_SUCCESS;
				message.setData(bundle);
				EventBus.getDefault().post(message);

			}
		}).start();

	}

	/**
	 * 根据第一级CCID获取缓存第二级目录集合
	 * 
	 * @return void
	 */
	public void getOfflineCacheFileList(final long folderCCID) {
		v(TAG, "getOfflineCacheFileList", "start folderCCID=" + folderCCID);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// 根据缓存层级类型填充缓存集合
				// 取文件集合
				ArrayList<OfflineCache> offlineCacheFileList = OfflineCacheFileDataBaseAdapter
						.getInstance().getOfflineCacheFileListByCCID(
								folderCCID, OfflineCache.CACHE_STATE_ALL);
				if (offlineCacheFileList != null) {
					for (OfflineCache offlineCacheFile : offlineCacheFileList) {

						L.v(TAG,
								"mergeOfflineCacheFolderList",
								"name="
										+ offlineCacheFile.getCacheName()
										+ offlineCacheFile.getCacheEpisodeNum()
										+ " downloadState="
										+ offlineCacheFile
												.getCacheDownloadState()
										+ " alreadySize="
										+ offlineCacheFile
												.getCacheAlreadySize()
										+ " totalSize="
										+ offlineCacheFile.getCacheTotalSize());
						offlineCacheFile
								.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FILE);
						// 取分片集合
						List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
								.getInstance()
								.getOfflineCacheFragmentListPlayableByPath(
										offlineCacheFile.getCacheStoragePath());
						if (offlineCacheFragmentList != null) {
							offlineCacheFile
									.setOfflineCacheFragmentList(offlineCacheFragmentList);
						}

					}
				}
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putParcelableArrayList(OfflineCache.OFFLINE_CACHE_LIST,
						offlineCacheFileList);
				message.what = StorageModule.MSG_FILE_CACHE_LIST_SUCCESS;
				message.setData(bundle);
				EventBus.getDefault().post(message);
			}
		}).start();
	}

	/**
	 * 
	 * 合并更多剧集下载状态
	 * 
	 * @param offlineCacheList
	 *            待合并集合
	 * @return List<OfflineCache>
	 */
	public List<OfflineCache> mergeMoreDramaDownloadStateByCID(
			List<OfflineCache> offlineCacheList) {
		for (OfflineCache offlineCache : offlineCacheList) {
			OfflineCacheFileDataBaseAdapter.getInstance().getOfflineCacheByCID(
					offlineCache);
			L.v(TAG,
					"mergeMoreDramaDownloadStateByCID",
					"name=" + offlineCache.getCacheName()
							+ offlineCache.getCacheEpisodeNum()
							+ " downloadState="
							+ offlineCache.getCacheDownloadState());
		}
		return offlineCacheList;
	}

	/**
	 * 
	 * 合并缓存文件夹
	 * 
	 * @return List<OfflineCache>
	 */
	public ArrayList<OfflineCache> mergeOfflineCacheFolderList() {
		// 取文件夹集合
		ArrayList<OfflineCache> offlineCacheFolderList = OfflineCacheFolderDataBaseAdapter
				.getInstance().getOfflineCacheFolderList();
		if (offlineCacheFolderList != null) {

			int i = 0;
			for (OfflineCache offlineCacheFolder : offlineCacheFolderList) {

				int finishCount = OfflineCacheFileDataBaseAdapter.getInstance()
						.getOfflineCacheFileFinishCountByCCID(
								offlineCacheFolder.getCacheCCID());
				offlineCacheFolder.setCacheFinishCount(finishCount);
				int allCount = OfflineCacheFileDataBaseAdapter.getInstance()
						.getOfflineCacheFileAllCountByCCID(
								offlineCacheFolder.getCacheCCID());
				offlineCacheFolder.setCacheAllCount(allCount);
				switch (offlineCacheFolder.getCacheContentType()) {
				// 剧集类视频
				case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
				case OfflineCache.CACHE_CONTENT_TYPE_TV:
				case OfflineCache.CACHE_CONTENT_TYPE_VARIETY: {
					// 取文件集合
					List<OfflineCache> offlineCacheFileList = OfflineCacheFileDataBaseAdapter
							.getInstance().getOfflineCacheFileListByCCID(
									offlineCacheFolder.getCacheCCID(),
									OfflineCache.CACHE_STATE_ALL);
					if (offlineCacheFileList != null) {
						for (OfflineCache offlineCacheFile : offlineCacheFileList) {

							L.v(TAG,
									"mergeOfflineCacheFolderList",
									"name="
											+ offlineCacheFile.getCacheName()
											+ offlineCacheFile
													.getCacheEpisodeNum()
											+ " downloadState="
											+ offlineCacheFile
													.getCacheDownloadState()
											+ " alreadySize="
											+ offlineCacheFile
													.getCacheAlreadySize()
											+ " totalSize="
											+ offlineCacheFile
													.getCacheTotalSize());
							offlineCacheFile
									.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FILE);
							// 取分片集合
							List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
									.getInstance()
									.getOfflineCacheFragmentListPlayableByPath(
											offlineCacheFile
													.getCacheStoragePath());
							if (offlineCacheFragmentList != null) {
								offlineCacheFile
										.setOfflineCacheFragmentList(offlineCacheFragmentList);
							}

							offlineCacheFolder
									.addOfflineCacheFile(offlineCacheFile);

						}
					}
					break;
				}
				default: {
					// 非剧集类视频
					// 取文件集合
					List<OfflineCache> offlineCacheFileList = OfflineCacheFileDataBaseAdapter
							.getInstance().getOfflineCacheFileListByCCID(
									offlineCacheFolder.getCacheCCID(),
									OfflineCache.CACHE_STATE_ALL);
					if (offlineCacheFileList != null) {
						for (OfflineCache offlineCacheFile : offlineCacheFileList) {

							L.v(TAG,
									"mergeOfflineCacheFolderList",
									"name="
											+ offlineCacheFile.getCacheName()
											+ offlineCacheFile
													.getCacheEpisodeNum()
											+ " downloadState="
											+ offlineCacheFile
													.getCacheDownloadState()
											+ " alreadySize="
											+ offlineCacheFile
													.getCacheAlreadySize()
											+ " totalSize="
											+ offlineCacheFile
													.getCacheTotalSize());
							offlineCacheFile
									.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FILE);
							// 取分片集合
							List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
									.getInstance()
									.getOfflineCacheFragmentListPlayableByPath(
											offlineCacheFile
													.getCacheStoragePath());
							if (offlineCacheFragmentList != null) {
								offlineCacheFile
										.setOfflineCacheFragmentList(offlineCacheFragmentList);
							}

							// 非剧集(非剧集直接替换folder为file)
							offlineCacheFolderList.set(i, offlineCacheFile);
						}
					}

					break;
				}
				}
				i++;
			}
		}
		return offlineCacheFolderList;
	}

	/**
	 * 
	 * 合并缓存文件(播放时使用)
	 * 
	 * @return OfflineCache
	 */
	public OfflineCache mergeOfflineCacheFile(long cid) {
		OfflineCache offlineCacheFile = OfflineCacheFileDataBaseAdapter
				.getInstance().getOfflineCacheFileByCID(cid);
		if (offlineCacheFile != null) {

			// 取分片集合
			List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
					.getInstance().getOfflineCacheFragmentListPlayableByPath(
							offlineCacheFile.getCacheStoragePath());
			if (offlineCacheFragmentList != null) {
				offlineCacheFile
						.setOfflineCacheFragmentList(offlineCacheFragmentList);
			}
		}

		return offlineCacheFile;
	}

	/**
	 * 
	 * 合并非剧集类型已下载完成缓存文件的分片连接
	 * 
	 * @return ArrayList<OfflineCache> 非剧集类型中的视频
	 */
	public ArrayList<OfflineCache> mergeCacheFileListStateFinishUnDrama() {

		// 取文件集合
		ArrayList<OfflineCache> offlineCacheFileList = OfflineCacheFileDataBaseAdapter
				.getInstance().getOfflineCacheFileListUnDramByStateFinish();
		if (offlineCacheFileList != null) {

			v(TAG, "mergeCacheFileListStateFinishUnDram",
					"offlineCacheFileList.size=" + offlineCacheFileList.size());

			int i = 0;
			for (OfflineCache offlineCacheFile : offlineCacheFileList) {

				// 取分片集合
				List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
						.getInstance()
						.getOfflineCacheFragmentListPlayableByPath(
								offlineCacheFile.getCacheStoragePath());
				if (offlineCacheFragmentList != null) {

					offlineCacheFile
							.setOfflineCacheFragmentList(offlineCacheFragmentList);
				} else {

					offlineCacheFileList.remove(i);

					e(TAG,
							"mergeCacheFileListStateFinishUnDram",
							"name=" + offlineCacheFile.getCacheName()
									+ offlineCacheFile.getCacheEpisodeNum()
									+ " cid=" + offlineCacheFile.getCacheCID()
									+ " ccid="
									+ offlineCacheFile.getCacheCCID()
									+ " downloadState="
									+ offlineCacheFile.getCacheDownloadState()
									+ " offlineCacheFragmentList=null");
				}
				i++;
			}

		} else {

			e(TAG, "mergeCacheFileListStateFinishUnDram",
					"offlineCacheFileList=null");
		}

		return offlineCacheFileList;
	}

	/**
	 * 
	 * 合并剧集类型已下载完成缓存文件的分片连接
	 * 
	 * @param offlineCache
	 *            剧集文件夹
	 * 
	 * @return ArrayList<OfflineCache> 剧集类型中的所有视频
	 */
	public ArrayList<OfflineCache> mergeCacheFileListStateFinishDrama(
			OfflineCache offlineCache) {
		// 取文件集合
		ArrayList<OfflineCache> offlineCacheFileList = OfflineCacheFileDataBaseAdapter
				.getInstance().getOfflineCacheFileListByCCID(
						offlineCache.getCacheCCID(),
						OfflineCache.CACHE_STATE_FINISH);

		if (offlineCacheFileList != null) {

			v(TAG, "mergeCacheFileListStateFinishDrama",
					"offlineCacheFileList.size=" + offlineCacheFileList.size());

			int i = 0;
			for (OfflineCache offlineCacheFile : offlineCacheFileList) {

				// 取分片集合
				List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
						.getInstance()
						.getOfflineCacheFragmentListPlayableByPath(
								offlineCacheFile.getCacheStoragePath());
				if (offlineCacheFragmentList != null
						&& offlineCacheFragmentList.size() > 0) {

					offlineCacheFile
							.setOfflineCacheFragmentList(offlineCacheFragmentList);
				} else {

					offlineCacheFileList.remove(i);

					e(TAG,
							"mergeCacheFileListStateFinishDrama",
							"name=" + offlineCache.getCacheName()
									+ offlineCache.getCacheEpisodeNum()
									+ " cid=" + offlineCache.getCacheCID()
									+ " ccid=" + offlineCache.getCacheCCID()
									+ "downloadState="
									+ offlineCache.getCacheDownloadState()
									+ " offlineCacheFragmentList.size=0");
				}
				i++;
			}
		} else {
			e(TAG, "mergeCacheFileListStateFinishDrama",
					"offlineCacheFileList=null");
		}

		return offlineCacheFileList;
	}

	/**
	 * 
	 * 合并已下载15%缓存文件的分片连接
	 * 
	 * @param offlineCache
	 *            缓存文件
	 * @return void
	 */
	public void mergeCacheFilePlayableByCID(OfflineCache offlineCache) {
		if (offlineCache == null) {
			return;
		}

		// 取分片集合
		List<OfflineCacheFragment> offlineCacheFragmentList = OfflineCacheFragmentDataBaseAdapter
				.getInstance().getOfflineCacheFragmentListPlayableByPath(
						offlineCache.getCacheStoragePath());
		if (offlineCacheFragmentList != null) {
			offlineCache.setOfflineCacheFragmentList(offlineCacheFragmentList);
		} else {
			L.e(TAG,
					"mergeCacheFilePlayableByCID",
					"name=" + offlineCache.getCacheName()
							+ offlineCache.getCacheEpisodeNum() + " ccid="
							+ offlineCache.getCacheCCID() + " cid="
							+ offlineCache.getCacheCID()
							+ " offlineCacheFragmentList=null");
		}

	}

	/**
	 * 
	 * 合并进度
	 * 
	 * @param offlineCacheFile
	 *            待合并缓存信息
	 * @return void
	 */
	public void mergeOfflineCache(OfflineCache offlineCacheFile) {
		// L.v(TAG,
		// "mergeOfflineCache",
		// "MSG_FILE_CACHE_LIST_SUCCESS name="
		// + offlineCacheFile.getCacheName()
		// + offlineCacheFile.getCacheEpisodeNum()
		// + " alreadySize="
		// + offlineCacheFile.getCacheAlreadySize()
		// + " totalSize=" + offlineCacheFile.getCacheTotalSize());
		OfflineCache offlineCacheFolder = null;
		// 第一层(文件夹)
		switch (offlineCacheFile.getCacheContentType()) {
		// 剧集类视频
		case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
		case OfflineCache.CACHE_CONTENT_TYPE_TV:
		case OfflineCache.CACHE_CONTENT_TYPE_VARIETY: {
			// 统计同组缓存文件
			offlineCacheFolder = new OfflineCache();
			// 加入剧集列表,增加总文件大小,并且更新进度
			offlineCacheFolder = new OfflineCache();
			offlineCacheFolder.setCacheCCID(offlineCacheFile.getCacheCCID());
			offlineCacheFolder.setCacheContentType(offlineCacheFile
					.getCacheContentType());
			offlineCacheFolder
					.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FOLDER);
			// 加入剧集列表,增加总文件大小,并且更新进度
			offlineCacheFolder.addOfflineCacheFile(offlineCacheFile);

			// 第二层(文件)
			Message fileListMessage = new Message();
			fileListMessage.what = StorageModule.MSG_FILE_CACHE_UPDATE_PROGRESS_SUCCESS;
			Bundle fileBundle = new Bundle();
			fileBundle.putParcelable(OfflineCache.OFFLINE_CACHE,
					offlineCacheFile);
			fileListMessage.setData(fileBundle);
			EventBus.getDefault().post(fileListMessage);
			break;
		}
		default:
			// 其他单文件视频
			offlineCacheFolder = offlineCacheFile;
			break;
		}

		offlineCacheFile
				.setCacheHierarchyType(OfflineCache.CACHE_HIERARCHY_FILE);

		// 第一层(文件夹)
		Message folderListMessage = new Message();
		folderListMessage.what = StorageModule.MSG_FOLDER_CACHE_UPDATE_PROGRESS_SUCCESS;
		Bundle folderBundle = new Bundle();
		folderBundle.putParcelable(OfflineCache.OFFLINE_CACHE,
				offlineCacheFolder);
		folderListMessage.setData(folderBundle);
		EventBus.getDefault().post(folderListMessage);

		// 发送存储空间检测通知
		Message spaceSizeMessage = new Message();
		Bundle spaceSizeBundle = new Bundle();
		spaceSizeBundle.putParcelable(OfflineCache.OFFLINE_CACHE,
				offlineCacheFile);
		spaceSizeMessage.setData(spaceSizeBundle);
		spaceSizeMessage.what = OfflineCacheModule.MSG_INTERNAL_CACHE_SPACE_SIZE_PROGRESS;
		EventBus.getDefault().post(spaceSizeMessage);

		// 发送可播放通知
		if (offlineCacheFile.getCacheIsPlay()) {

			Message msg = new Message();
			msg.what = StorageModule.MSG_DOWNLOAD_PREPARE_ONLINE_CACHE_SUCCESS;
			Bundle bundle = new Bundle();
			bundle.putParcelable(OfflineCache.OFFLINE_CACHE, offlineCacheFile);
			msg.setData(bundle);
			EventBus.getDefault().post(msg);
		}

		// L.v(TAG,
		// "mergeOfflineCache",
		// "MSG_INTERNAL_FOLDER_CACHE_LIST_SUCCESS name="
		// + offlineCacheFile.getCacheName()
		// + offlineCacheFile.getCacheEpisodeNum());
	}

	/**
	 * 
	 * 添加任务成功
	 * 
	 * @param offlineCacheFileList
	 *            成功任务的集合
	 * @param cacheFromPage
	 *            添加缓存来自于哪个页面
	 * @return void
	 */
	public void addCacheSuccess(List<OfflineCache> offlineCacheFileList) {

		// 添加任务成功,建立第一级目录

		// 建立第一级目录(新建文件夹,已经做了重复目录过滤处理)
		OfflineCacheFolderDataBaseAdapter.getInstance().addOfflineCacheFolder(
				offlineCacheFileList);
		// 建立第二级目录(新建文件)
		OfflineCacheFileDataBaseAdapter.getInstance().addOfflineCacheFileList(
				offlineCacheFileList);

		mIsAddSuccess = true;

		// 刷新文件列表(更多剧集界面添加)
		if (offlineCacheFileList != null && offlineCacheFileList.size() > 0) {

			OfflineCache offlineCacheFile = offlineCacheFileList.get(0);

			L.v(TAG, "addCacheSuccess",
					"refresh offlineCacheFileList cacheFromPage="
							+ offlineCacheFile.getCacheFromPage());

			StorageModule.getInstance().getCacheFileListByCCID(
					offlineCacheFile.getCacheCCID());

		} else {

			L.v(TAG, "addCacheSuccess", "refresh offlineCacheFileList=null");

		}
	}

	/**
	 * 
	 * 缓存进度处理方法
	 * 
	 * @param msg
	 *            订阅消息
	 * @return void
	 */
	public void onEventBackgroundThread(Message msg) {
		Bundle bundle = null;
		switch (msg.what) {
		case MSG_INTERNAL_CACHE_SPACE_SIZE_PROGRESS:
			// L.v(TAG, "onEventBackgroundThread",
			// "MSG_INTERNAL_CACHE_SPACE_SIZE_PROGRESS");
			bundle = msg.getData();
			if (bundle == null) {
				return;
			}
			long currentSize = bundle
					.getLong(OfflineCache.OFFLINE_CACHE_CURRENT_SIZE);
			// 做存储检测,通知UI
			CacheDownloadManager.getInstance().checkManyStorageSpace(
					currentSize);
			break;
		case OfflineCacheModule.MSG_INTERNAL_FILE_CACHE_DELETE_SUCCESS: {
			L.v(TAG, "onEventBackgroundThread",
					"MSG_INTERNAL_FILE_CACHE_DELETE_SUCCESS");
			mIsDeleteSuccess = true;

			break;
		}
		case StorageModule.MSG_CACHE_START_ALL_SUCCESS:
			L.v(TAG, "onEventBackgroundThread", "MSG_CACHE_START_ALL_SUCCESS");
			mIsShieldStartAllOperate = false;
			L.v(TAG, "onEventBackgroundThread", "end startCacheAll");
			// 成功一个,就执行下一个等待的操作
			operateCacheQueue();
			break;
		case StorageModule.MSG_CACHE_PAUSE_ALL_SUCCESS:
			L.v(TAG, "onEventBackgroundThread", "MSG_CACHE_PAUSE_ALL_SUCCESS");
			mIsShieldPauseAllOperate = false;
			L.v(TAG, "onEventBackgroundThread", "end pauseCacheAll");
			// 成功一个,就执行下一个等待的操作
			operateCacheQueue();
			break;
		case StorageModule.MSG_DOWNLOAD_CACHE_SUCCESS:
			// 刷新进度
			getOfflineCacheFolderList();
			break;
		case StorageModule.MSG_ADD_CACHE_SUCCESS: {
			L.v(TAG, "onEventBackgroundThread", "MSG_ADD_CACHE_SUCCESS");
			bundle = msg.getData();
			if (bundle == null) {
				return;
			}
			List<OfflineCache> offlineCacheAddFileList = bundle
					.getParcelableArrayList(OfflineCache.OFFLINE_CACHE_LIST);
			if (offlineCacheAddFileList != null
					&& offlineCacheAddFileList.size() > 0) {

				L.v(TAG, "onEventBackgroundThread",
						"MSG_ADD_CACHE_SUCCESS offlineCacheAddFileList.size="
								+ offlineCacheAddFileList.size());

				addCacheSuccess(offlineCacheAddFileList);

			} else {

				L.v(TAG, "onEventBackgroundThread",
						"MSG_ADD_CACHE_SUCCESS offlineCacheAddFileList=null");

			}

			break;
		}
		case StorageModule.MSG_ADD_CACHE_FAIL:
			L.v(TAG, "onEventBackgroundThread", "MSG_ADD_CACHE_FAIL timeout");
			bundle = msg.getData();
			if (bundle == null) {
				return;
			}
			break;
		default:
			break;
		}

	}

	/**
	 * 
	 * 删除视频和配置文件
	 * 
	 * @param offlineCache
	 *            视频信息
	 * @return void
	 */
	public synchronized void deleteOfflineCacheFile(OfflineCache offlineCache) {
		L.v(TAG,
				"delete",
				"name=" + offlineCache.getCacheName()
						+ offlineCache.getCacheEpisodeNum() + " filePath="
						+ offlineCache.getCacheStoragePath());

		switch (offlineCache.getCacheContentType()) {
		// 剧集类视频
		case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
		case OfflineCache.CACHE_CONTENT_TYPE_TV:
		case OfflineCache.CACHE_CONTENT_TYPE_VARIETY: {
			switch (offlineCache.getCacheHierarchyType()) {
			case OfflineCache.CACHE_HIERARCHY_FILE:

				String storagePath = offlineCache.getCacheStoragePath();

				if (storagePath != null && !storagePath.equals("")) {
					// 删除视频文件夹
					DownloadUtil.deleteDirectory(offlineCache
							.getCacheStoragePath());
					// 删除空文件夹
					DownloadUtil.deleteEmptyDirectory(3, storagePath);
				}

				break;
			case OfflineCache.CACHE_HIERARCHY_FOLDER:
				// 此版本没有删除folder的情况,增加此需求时再添加
				break;
			default:
				break;
			}
			break;
		}
		default:
			// 非剧集
			String storagePath = offlineCache.getCacheStoragePath();
			if (storagePath != null && !storagePath.equals("")) {
				// 删除视频文件夹
				DownloadUtil
						.deleteDirectory(offlineCache.getCacheStoragePath());
				// 删除空文件夹
				DownloadUtil.deleteEmptyDirectory(3, storagePath);
			}

			break;
		}

	}

	/**
	 * 开启后台离线缓存服务
	 * 
	 * @return void
	 */
	public void startCacheService() {

		CacheDownloadManager.getInstance().startCacheService();
	}

	/**
	 * 停止后台离线缓存服务
	 * 
	 * @return void
	 */
	public void stopCacheService() {
		CacheDownloadManager.getInstance().stopCacheService();
	}

	/**
	 * 
	 * 开始发送数据
	 * 
	 * @return void
	 */
	public void startSendOfflineCacheMessage() {
		v(TAG, "startSendOfflineCacheMessage", "start");
		// 文件和文件夹列表都发送
		// sendOfflineCacheList(OfflineCache.CACHE_HIERARCHY_ALL);
	}

	/**
	 * 
	 * 停止发送数据
	 * 
	 * @return void
	 */
	public void stopSendOfflineCacheMessage() {
		v(TAG, "stopSendOfflineCacheMessage", "start");
	}

	void v(String tag, String type, String msg) {
		if (StorageConfig.CACHE_MODULE_LOG) {
			L.v(tag, type, msg);
		}
	}

	void e(String tag, String type, String msg) {
		if (StorageConfig.CACHE_MODULE_LOG) {
			L.e(tag, type, msg);
		}
	}

	void writeOfflineCacheLog(String method, OfflineCache offlineCache) {
		L.v(TAG,
				method,
				" name=" + offlineCache.getCacheName()
						+ offlineCache.getCacheEpisodeNum() + " errorCode="
						+ offlineCache.getCacheErrorCode() + " downloadState="
						+ offlineCache.getCacheDownloadState() + " ccid="
						+ offlineCache.getCacheCCID() + " cid="
						+ offlineCache.getCacheCID() + " contentType="
						+ offlineCache.getCacheContentType() + " alreadySize="
						+ offlineCache.getCacheAlreadySize() + " totalSize="
						+ offlineCache.getCacheTotalSize());
	}

	void writeOfflineCacheListLog(String method,
			List<OfflineCache> offlineCacheList) {

		if (offlineCacheList == null) {
			return;
		}

		for (OfflineCache offlineCache : offlineCacheList) {
			L.v(TAG,
					method,
					" name=" + offlineCache.getCacheName()
							+ offlineCache.getCacheEpisodeNum() + " subSize="
							+ offlineCache.getOfflineCacheList().size()
							+ " errorCode=" + offlineCache.getCacheErrorCode()
							+ " downloadState="
							+ offlineCache.getCacheDownloadState() + " ccid="
							+ offlineCache.getCacheCCID() + " cid="
							+ offlineCache.getCacheCID() + " contentType="
							+ offlineCache.getCacheContentType()
							+ " alreadySize="
							+ offlineCache.getCacheAlreadySize()
							+ " totalSize=" + offlineCache.getCacheTotalSize());
		}
	}

	public static class CacheOperate {
		public boolean mIsUpdateDownloadState;
		public int mCacheOperateType;
	}
}
